package demoApiOfKboot.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;


/**
 *第二种文件下载方式demo
 * @author caix
 *
 */
@RestController
public class DownLoadFile2DemoAction {
	
	@RequestMapping(value="/download2", method=RequestMethod.GET)  
    public void getDownload(Long id, HttpServletRequest request, HttpServletResponse response) {  
  
        String fullPath = "E:/" + id +".zip";  
        File downloadFile = new File(fullPath);  
  
        ServletContext context = request.getServletContext();  
  
        // get MIME type of the file  
        String mimeType = context.getMimeType(fullPath);  
        if (mimeType == null) {  
            // set to binary type if MIME mapping not found  
            mimeType = "application/octet-stream";  
            System.out.println("context getMimeType is null");  
        }  
        System.out.println("MIME type: " + mimeType);  
  
        // set content attributes for the response  
        response.setContentType(mimeType);  
        response.setContentLength((int) downloadFile.length());  
  
        // set headers for the response  
        String headerKey = "Content-Disposition";  
        String headerValue = String.format("attachment; filename=\"%s\"",  
                downloadFile.getName());  
        response.setHeader(headerKey, headerValue);  
  
        // Copy the stream to the response's output stream.  
        try {  
            InputStream myStream = new FileInputStream(fullPath);  
            IOUtils.copy(myStream, response.getOutputStream());  
            response.flushBuffer();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
}